package imgutil

import (
	"io"
	"os"
	"fmt"
	"errors"
	"image"
	"image/jpeg"
	"image/png"
	"github.com/golang/glog"
)

const (
	SignTypePng = iota
	SignTypeJpg
)

const (
	IMAGE_TYPE_JPG = "jpg"
	IMAGE_TYPE_PNG = "png"
	IMAGE_TYPE_GIF = "gif"
	IMAGE_TYPE_BMP = "bmp"
)

//获取文件类型
func GetImageType(f io.Reader) (imageType string, err error) {
	bytes := make([]byte, 4)
	n, err := f.Read(bytes)
	if (err != nil) {
		return "", err
	}
	defer f.(io.ReadSeeker).Seek(0, os.SEEK_SET)
	
	if n < 4 {
		return "", fmt.Errorf("image read faild.")
	}
	if bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E && bytes[3] == 0x47 {
		return IMAGE_TYPE_PNG, nil
	}
	if bytes[0] == 0xFF && bytes[1] == 0xD8 {
		return IMAGE_TYPE_JPG, nil
	}
	if bytes[0] == 0x47 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[3] == 0x38 {
		return IMAGE_TYPE_GIF, nil
	}
	if bytes[0] == 0x42 && bytes[1] == 0x4D {
		return IMAGE_TYPE_BMP, nil
	}
	return "", fmt.Errorf("unknow image type.")
}

func GetImageHeight(input io.Reader, format int) (height int, err error) {
	var (
		img      image.Image
	)
	switch format {
	case SignTypePng:
		img, err = png.Decode(input)
	case SignTypeJpg:
		img, err = jpeg.Decode(input)
	default:
		err = errors.New("not support format, now support png,jpeg")
	}
	if err != nil {
		glog.Errorf("image decode error(%v)", err)
		return
	}
	height = img.Bounds().Dy()
	return
}
